#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Plugin demo escrito por Diego Hahn - 2010

import gtk

import struct
import os
import tempfile

import pluginmanager
import compression

@pluginmanager.register('PLUGIN-REGISTER')
def deflate_register(*args, **kwargs):
    return {'??DEFLATE??':'DEFLATE'}

@pluginmanager.register('DEFLATE-SCAN')
def deflate_scan(*args, **kwargs):
    fd = kwargs['file']
    progbar = kwargs['progbar']

    results1 = []
    results2 = []
    fd.seek(0,0)
    map = fd.read()

    address = 0
    while True:
        try:
            header = struct.unpack('<L', map[address:address+4])[0]
            size = header >> 8
            flag = header & 0xFF
            if flag in (0x24, 0x28) and size < 65536:
                if compression.huffman.try_uncompress(map, address, size):
                    percent = float(address)/float(os.path.getsize(fd.name))
                    progbar.set_text('DEFLATE: ' + str(int(percent * 50)) + "%")
                    progbar.set_fraction(percent/2)

                    while gtk.events_pending():
                        gtk.main_iteration()

                    results1.append(address)
            address += 4
        except:
            break


    for x in range(len(results1)):
        temp = tempfile.NamedTemporaryFile(delete=True)
        buffer = compression.huffman.uncompress(fd, results1[x])
        buffer.tofile(temp.file)
        temp.seek(0,0)
        try:
            buffer = compression.lzss.uncompress(temp, 0)
            if buffer:
                percent = float(x)/float(len(results1))
                progbar.set_text('DEFLATE: ' + str(int(50 + percent * 50)) + "%")
                progbar.set_fraction(0.5 + percent/2)

                while gtk.events_pending():
                    gtk.main_iteration()

                results2.append((results1[x], 'DEFLATE'))
        except:
            pass
        temp.close()

    return results2

@pluginmanager.register('DEFLATE-DECODER')
def deflate_decode(*args, **kwargs):
    address = kwargs['address']
    fd = kwargs['file']

    buffer = compression.huffman.uncompress(fd, address)

    temp = tempfile.NamedTemporaryFile(delete=False)
    buffer.tofile(temp.file)

    buffer = compression.lzss.uncompress(temp, 0)
    temp.close()

    return buffer

